#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <sys/socket.h>
#include <unistd.h>

#define PORT 8080

int main()
{
    struct sockaddr_in serv_addr;
    int sock = 0, valread;
    struct sockaddr_in serv_addr_in;
    std::string hello = "hello";
    char buffer[1024] = { 0 };

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        std::cout << "\n Socket creation error \n";
        return -1;
    }

    serv_addr_in.sin_family = AF_INET;
    serv_addr_in.sin_port = htons(PORT);

    // 将 IPv4 地址从文本转换为二进制形式
    if (inet_pton(AF_INET, "127.0.0.1", &serv_addr_in.sin_addr) <= 0) {
        std::cout << "\nInvalid address/ Address not supported \n";
        return -1;
    }

    // 连接到服务器
    if (connect(sock, (struct sockaddr*)&serv_addr_in, sizeof(serv_addr_in)) < 0) {
        std::cout << "\nConnection Failed \n";
        return -1;
    }

    // 发送数据
    send(sock, hello.data(), hello.length(), 0);

    // 接收数据
    valread = read(sock, buffer, 1024);
    std::cout << buffer << std::endl;

    // 关闭 socket
    close(sock);
    return 0;
}
